﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using elfam.web.Dao;
using elfam.web.Models;
using elfam.web.Paging;
using Microsoft.Practices.Unity;
using NHibernate.Criterion;

namespace elfam.web.Controllers
{
    public class BaseController: Controller
    {
        protected IDaoTemplate daoTemplate;

       [Dependency]
        public IDaoTemplate DaoTemplate
        {
            set { daoTemplate = value; }
        }

        protected User CurrentUser()
        {
            if (!string.IsNullOrEmpty(User.Identity.Name))
            {
                return daoTemplate.FindUniqueByField<User>(Models.User.EmailProperty, User.Identity.Name);
            }
            return null;
        }

        public PagingResult<T> Paging<T>(DetachedCriteria criteria, int page, int pageSize)
        {
            int start = (page - 1) * pageSize + 0;
            IList<T> records = daoTemplate.FindByCriteria<T>(criteria, start, pageSize);
            DetachedCriteria countCriteria = DetachedCriteria.For<T>();
            int total = daoTemplate.GetCount(countCriteria);
            PagingInfo pagingInfo = new PagingInfo
                                        {
                CurrentPage = page,
                TotalPages = (int)Math.Ceiling((double)total / pageSize)
            };
            return new PagingResult<T>
                       {
                Records = records,
                PagingInfo = pagingInfo
            };
        }
    }
}
